// 包装组件，做一些通用的操作
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'umi';
import { withRouter } from 'umi';
import { history } from 'umi';
import { Card, Tag, Steps, Form, Row, Col, Button, message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import request from '@/utils/request';
import { withRoutePage } from '@/utils/enhanceUtils';
import { countryDict } from '@/models/mineList';
import { readStatusMap, useSetReadStatus } from '@/hooks/useSetReadStatus';

import { useDetail } from './utils';
// import AuthCode from '@/utils/auth/AuthCode';
// import AuthComponent from '@/utils/auth/AuthComponent';
// import BasicInfo from './components/BasicInfo';
import FormElement from './FormElement';
import styles from './Wrap.less';
// import { getTwoToneColor } from 'antd/lib/icon/twoTonePrimaryColor';

const { Step } = Steps;
const { Item } = Form;

const processPush = async data => {
    const response = await request('/api/oa/v1/system/process/push', {
        method: 'POST',
        data
    });
    return response;
};

const RegularizationDetails = props => {
    const { form, location, formItemLayout, tailFormItemLayout, user } = props;
    const {
        query: { processTemplateId, processInstanceId, regularId, type }
    } = location;
    const [submitLoading, setSubmitLoading] = useState(false);
    const [rejectLoading, setRejectLoading] = useState(false);
    const [cancelLoading, setCancelLoading] = useState(false);
    const [saveLoading, setSaveLoading] = useState(false);
    const initialDetail = regularId
        ? { regularId, processInstanceId: '', processTemplateId: '', user, type }
        : { regularId: '', processInstanceId, processTemplateId, user, type };
    const { detail, loading } = useDetail(initialDetail);
    const {
        processTaskInstances,
        processState,
        processTaskTemplates,
        currentProcessTaskInstance,
        currentProcessTaskInstance: {
            // assigneeEmployeeNames,
            relatedBusinessObject,
            taskPath = '',
            assigneeEmployeeIds = ''
        },
        startAssigneeEmployeeId
    } = detail;

    const { currentUser } = user;
    const {
        id: relatedBusinessObjectId,
        companyId,
        employeeName,
        employeeId,
        departmentId,
        postId,
        currentProcessTasDesc = '',
        hrApproval = '',
        lastConfirmDate
    } = relatedBusinessObject;
    // 保存
    const handleSave = async () => {
        const allData = form.getFieldsValue();
        const { workDesc, outstandingPerformance, improve } = allData;
        const newData = [workDesc, outstandingPerformance, improve];
        const haveData = newData.some(item => !!item);
        if (!haveData) return message.warning('不能保存空表单！');
        setSaveLoading(true);
        const saveResult = await request('/api/oa/v1/regular/save', {
            method: 'POST',
            data: {
                id: relatedBusinessObjectId || '',
                companyId,
                employeeId,
                departmentId,
                postId,
                ...allData
            }
        });
        if (saveResult.code !== 10000) {
            setSaveLoading(false);
            return message.error(saveResult.msg);
        }
        message.success('保存成功！');
        setSaveLoading(false);
        return history.go(-1);
    };
    const isStarter = !startAssigneeEmployeeId || startAssigneeEmployeeId === `${currentUser.id}`;
    const current = regularId ? taskPath.length / 3 - 1 : 0;
    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            // const ret = form.getFieldsValue()
            // return false
            if (!err) {
                setSubmitLoading(true);
                // 只要当前用户是发起人,且在第一步，就要做onlycheck校验
                if (isStarter && current === 0) {
                    const checkResponse = await request('/api/oa/v1/regular/actions/onlycheck');
                    if (checkResponse.code !== 10000) {
                        message.error(checkResponse.msg);
                        setSubmitLoading(false);
                        return;
                    }
                }
                const data = {
                    id: regularId || '',
                    currentAction: 'forwardToNextTask',
                    processTemplateId: regularId ? detail.processTemplateId : processTemplateId,
                    processInstanceId: regularId ? detail.processInstanceId : processInstanceId,
                    // relatedBusinessKey: `afterDepartmentId:${afterDepartmentId || detail.afterDepartmentId},`,
                    relatedBusinessObject: {
                        id: relatedBusinessObjectId,
                        companyId,
                        employeeId,
                        departmentId,
                        postId,
                        ...values
                        // transferDate: values.transferDate.format('YYYY-MM-DD'),
                        // id: relatedBusinessObject.id || ''
                    }
                };
                if (processInstanceId) data.processInstanceId = processInstanceId;
                // console.info('#/////////////提交的数据data:', data);
                const response = await processPush(data);
                if (response.code === 10000) {
                    message.success('提交成功！');
                    history.push('/personal/portal/myOnboardAndLeave/myRegularization');
                } else {
                    message.error(response.msg);
                    setSubmitLoading(false);
                }
            }
        });
    };
    // const isFirstStep = detail.startAssigneeEmployeeId === `${currentUser.id}`;
    const getDescription = title => {
        const find = curCompanyId => countryDict.find(country => country.id === curCompanyId);
        return [title, find(companyId) && find(companyId).name, employeeName].join('-');
    };

    const handleReject = async () => {
        setRejectLoading(true);
        const { companyId: curCompanyId } = form.getFieldsValue();
        const data = {
            currentAction: 'backwardToPreviousTask',
            processTemplateId: detail.processTemplateId,
            processInstanceId: detail.processInstanceId,
            // id: regularId || '',
            relatedBusinessObject: {
                id: relatedBusinessObjectId,
                employeeId,
                companyId: curCompanyId
            }
        };

        console.info('data:', data);
        const response = await processPush(data);
        if (response.code === 10000) {
            message.success('退回成功！');
            history.push('/personal/portal/myOnboardAndLeave/myRegularization');
        } else {
            message.error(response.msg);
            setRejectLoading(false);
        }
    };
    const handleCancel = async () => {
        if (!regularId) {
            history.push('/personal/portal/flow/mine/list');
        } else {
            setCancelLoading(true);
            const response = await processPush({
                currentAction: 'resetToFirstTask',
                id: regularId || '',
                processTemplateId: detail.processTemplateId,
                processInstanceId: detail.processInstanceId
            });

            if (response.code === 10000) {
                message.success('撤销成功！');
                history.push('/personal/portal/flow/mine/list');
            } else {
                message.error(response.msg);
                setCancelLoading(false);
            }
        }
    };

    const getStatus = (taskTemplateId, index) => {
        if (detail.processState === 'success') return 'finish';
        if (!regularId) {
            if (index === 0) {
                return 'process';
            }
            return 'wait';
        }

        if (current === index) return 'process';
        if (index < current) return 'finish';
        const find = processTaskInstances.find(item => item.taskTemplateId === taskTemplateId);

        if (find && find.assigneeAction === 'backwardToPreviousTask') {
            return 'error';
        }
        return 'wait';
    };
    const cancelButton = (
        <Button loading={cancelLoading} onClick={handleCancel} className={styles.nextBtn}>
            撤销
        </Button>
    );

    const btns = (
        // <Item style={{ marginBottom: 4 }} label=" " colon={false}>
        <Item {...tailFormItemLayout}>
            <Button loading={submitLoading} type="primary" onClick={handleSubmit}>
                提交
            </Button>
            {/* 是发起人 */}
            {(!startAssigneeEmployeeId || startAssigneeEmployeeId === `${currentUser.id}`) && current === 0 && (
                <Button loading={saveLoading} onClick={handleSave} className={styles.nextBtn}>
                    保存
                </Button>
            )}
            {/* 新增时、被退回时、且是发起人 */}
            {(!regularId || detail.processState === 'failed') &&
                startAssigneeEmployeeId === `${currentUser.id}` &&
                current === 0 &&
                cancelButton}
            {/* 当前操作人且处于编辑，且不能是第一步 */}
            {regularId && assigneeEmployeeIds.split(',').includes(`${currentUser.id}`) && taskPath.length !== 3 && (
                <Button loading={rejectLoading} onClick={handleReject} className={styles.nextBtn}>
                    退回
                </Button>
            )}
        </Item>
    );
    const formElementProps = {
        // user: relatedBusinessObject,
        user: user.currentUser,
        form,
        btns,
        detail,
        location,
        formItemLayout,
        tailFormItemLayout
    };
    const trimHeadComma = str => {
        if (!str) return '';
        if (str.substring(0, 1) === ',') {
            return str.slice(1);
        }
        return str;
    };
    const instanceList = [currentProcessTaskInstance, ...processTaskInstances];
    const assigneeEmployeeNamesList = () => {
        const rt = [];
        processTaskTemplates.forEach(item => {
            const targetItem = instanceList.find(instanceItem => instanceItem.taskTemplateId === item.taskTemplateId);
            if (targetItem) {
                rt.push(trimHeadComma(targetItem.assigneeEmployeeNames));
            }
        });
        if (rt.length === 0) rt.push(currentUser.employeeName);
        return rt;
    };
    const getTaskDescColor = () => {
        if (processState === 'success') {
            return hrApproval === 0 ? 'green' : 'red';
        }
        return 'orange';
    };
    const getProcessTitle = (index, taskName) => {
        if (!assigneeEmployeeNamesList()[index]) {
            return taskName;
        }
        return index > 0 ? '转正评估' : '转正申请';
    };
    const getProcessDescription = (taskTemplateId, status, index) => {
        if (processTaskInstances.length === 0 && index === 0) {
            return user.currentUser.employeeName;
        }
        const targetInstance = instanceList.find(item => item.taskTemplateId === taskTemplateId);
        if (targetInstance) {
            const { assigneeEmployeeNames: assigneeNames = '', actualAssigneeEmployeeName = '' } = targetInstance;
            return status === 'error'
                ? `${actualAssigneeEmployeeName}（已退回）`
                : actualAssigneeEmployeeName || trimHeadComma(assigneeNames) || '';
        }
        return '';
    };

    useSetReadStatus({ id: processInstanceId, type: readStatusMap.REGULAR });

    return (
        <PageHeaderWrapper type="success">
            <Card loading={loading} bordered={false}>
                <Row className={styles.titleBox} type="flex">
                    <Col>
                        <h3 className={styles.title}>{getDescription(regularId ? '转正详情' : '转正申请')}</h3>
                    </Col>
                    {!!regularId && lastConfirmDate && (!isStarter || processState === 'doing') && (
                        <>
                            <Col>
                                <Tag color={getTaskDescColor()} className={styles.status}>
                                    {currentProcessTasDesc}
                                    {/* {getTagLabel()} */}
                                </Tag>
                            </Col>
                            <Col>
                                <span className={styles.time}>最晚确认时间 {lastConfirmDate}</span>
                            </Col>
                        </>
                    )}
                    {processState === 'success' && (
                        <Tag color={getTaskDescColor()} className={styles.status}>
                            {currentProcessTasDesc}
                        </Tag>
                    )}
                </Row>
                <Steps className={styles.steps}>
                    {processTaskTemplates.map(({ id, taskName, taskTemplateId }, index) => {
                        const status = getStatus(taskTemplateId, index);
                        return (
                            <Step
                                status={status}
                                title={getProcessTitle(index, taskName)}
                                description={getProcessDescription(taskTemplateId, status, index)}
                                key={id}
                            />
                        );
                    })}
                </Steps>
                <Form className={styles.form} {...formItemLayout}>
                    <FormElement {...formElementProps}></FormElement>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

RegularizationDetails.propTypes = {
    formElement: PropTypes.func.isRequired,
    formItemLayout: PropTypes.object,
    tailFormItemLayout: PropTypes.object
};

RegularizationDetails.defaultProps = {
    formItemLayout: {
        labelCol: {
            sm: { span: 24 },
            md: { span: 4 }
        },
        wrapperCol: {
            sm: { span: 24 },
            md: { span: 10 }
        }
    },
    tailFormItemLayout: {
        wrapperCol: {
            sm: {
                span: 24,
                offset: 0
            },
            md: {
                span: 8,
                offset: 4
            }
        }
    }
};

export default withRoutePage(
    connect(props => ({
        user: props.user
    }))(Form.create()(withRouter(RegularizationDetails)))
);
